<?php
/**
 * POST请求
 */
function http_post($url, $params,$contentType=false)
{

    if (function_exists('curl_init')) { // curl方式
        $oCurl = curl_init();
        if (stripos($url, 'https://') !== FALSE) {
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
        }
        $string = $params;
        if (is_array($params)) {
            $aPOST = array();
            foreach ($params as $key => $val) {
                $aPOST[] = $key . '=' . urlencode($val);
            }
            $string = join('&', $aPOST);
        }
        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($oCurl, CURLOPT_POST, TRUE);
        //$contentType json处理
        if($contentType){
            $headers = array(
                "Content-type: application/json;charset='utf-8'",
            );

            curl_setopt($oCurl, CURLOPT_HTTPHEADER, $headers);
            curl_setopt($oCurl, CURLOPT_POSTFIELDS, json_encode($params));
        }else{
            curl_setopt($oCurl, CURLOPT_POSTFIELDS, $string);
        }
        $response = curl_exec($oCurl);
        curl_close($oCurl);
        return $response;
//        return json_decode($response, true);
    } elseif (function_exists('stream_context_create')) { // php5.3以上
        $opts = array(
            'http' => array(
                'method' => 'POST',
                'header' => 'Content-type: application/x-www-form-urlencoded',
                'content' => http_build_query($params),
            )
        );
        $_opts = stream_context_get_params(stream_context_get_default());
        $context = stream_context_create(array_merge_recursive($_opts['options'], $opts));
        return file_get_contents($url, false, $context);
//        return json_decode(file_get_contents($url, false, $context), true);
    } else {
        return FALSE;
    }
}

/**
 * 生成签名
 * @param $params
 * @param $key
 * @param string $encryptType
 * @return string
 */
function hmacRequest($params, $key, $encryptType = "1")
{
    if ("1" == $encryptType) {
        return md5(implode("", $params) . $key);
    } else {
        $private_key = openssl_pkey_get_private($key);
        $params = implode("", $params);
        openssl_sign($params, $sign, $private_key, OPENSSL_ALGO_MD5);
        openssl_free_key($private_key);
        $sign = base64_encode($sign);
        return $sign;
    }

}


/**
 *  批量代付生成签名，由于批量代付包含details的字段，需要特殊处理
 * @param $params
 * @param $key
 * @param string $encryptType
 * @return string
 */
function batchHmacRequest($params, $key, $encryptType = "1")
{
    $details=$params['details'];
    unset($params['details']);
    $detailsStr='';
    foreach ($details as $k=>$value){
        $detailsStr.= implode("", $value);
    }
    if ("1" == $encryptType) {
        return md5(implode("", $params) . $detailsStr . $key);
    } else {
        $private_key = openssl_pkey_get_private($key);
        $params = implode("", $params).$detailsStr;
        openssl_sign($params, $sign, $private_key, OPENSSL_ALGO_MD5);
        openssl_free_key($private_key);
        $sign = base64_encode($sign);
        return $sign;
    }

}




//生成订单号
function getOrderId()
{
    return date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
}

/**
 * 生成批量代付detail
 *
 *$detail=array(
 * 0=>array(
 *         1, //detailId
 *          '张三',//payee
 *          '6228480402564890018'，//'bankacount'
 *         '0.1',// 'money'
 *          '代付接口测试1',//'desc'
 *         '广州市',// 'city'
 *          0,//'isVerify'
 *          1,//'PublicOrPrivate'
 *         102902500019,// 'num'
 *      )
 *
 * )
 * return str
 *
 * example
 *  代付明细序号(必填)|收款人姓名(必填)|收款银行帐号(必填)|代付金额(必填)|代付说明|收款银行所在城市(必填)|是否审核(1:审核 0:不审核)|对公对私(1:对公 2:对私)|联行号(对公必填)
 *  1001|张三|6228480402564890018|10.01|代付接口测试1|广州市|1|1|102902500019^1001|李四|6228480402564890018|10.01|代付接口测试2|广州市|1|1|102902500019
 **/
function getProxyPayDetail(Array $detail)
{
    $result = '';
    foreach ($detail as $key => $item) {
        if ($key != 0) {
            $result .= '^';
        }

        $result .= implode('|', array_values($item));

    }
    return $result;
}


function decodeUnicode($str)
{
    return preg_replace_callback('/\\\\u([0-9a-f]{4})/i',
        create_function(
            '$matches',
            'return mb_convert_encoding(pack("H*", $matches[1]), "UTF-8", "UCS-2BE");'
        ),
        $str);
}

function output($str){
    echo '<pre>'.decodeUnicode(json_encode(json_decode($str), JSON_PRETTY_PRINT)).'</pre>';
}




/**
 *   判断文件是是否是图片
 * @param $fileName
 * @param $fileTmpName
 *  @return bool true|false
 */
function checkIsImage($fileName,$fileTmpName){

    if( !in_array(substr(strrchr ( $fileName , "." ),1), array('jpg','png','bmp','jpeg')) || !getimagesize($fileTmpName)){
        return false;
    }
    return true;
}

/**
 * 获取图片的base64
 * @param $file  $_FILES["file"]["tmp_name"]
 * @param $type  png/
 * @return string
 */
function getImageBase64($file,$type){
    $bin_string = file_get_contents($file);
    return 'data:' . $type . ';base64,' . base64_encode($bin_string);
}


/**
 * 生成批次id
 * @param $length
 * @return string
 */
function getBatchId()
{
   return "batch".getOrderId();
}